//
//  CNSearchViewController.m
//  BeeQuick_19
//
//  Created by whong7 on 16/9/23.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "CNSearchViewController.h"
#import "CNHotView.h"
#import "CNSearchView.h"
#import "CNSearchViewCell.h"


@interface CNSearchViewController ()<CAAnimationDelegate>

@property(nonatomic,weak)UISearchBar *searchBar;
@property(nonatomic,strong)CNHotView *hotView ;
@property(nonatomic,strong)CNSearchView *searchView;
@property(nonatomic,strong)UIView *carView;

@property(nonatomic,strong)CNSearchViewCell *selectedCell;
@property(nonatomic,strong)UIImageView *selecedImageView;


@property(nonatomic,strong)UILabel *countLabel;
@property(nonatomic,strong)UIImageView *redV;
@property(nonatomic,assign)NSInteger count;


@end

@implementation CNSearchViewController

#pragma mark - tabBar处理
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;

}
#pragma mark - 程序入口
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHex:0xefefef];
    [self setNav];
    [self setupUI];
    [self setNoti];
    

   
}
#pragma mark -  注册通知
-(void)setNoti
{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addButtonClick:) name:@"点击加号" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buyCarCount:) name:@"购物车" object:nil];
}
#pragma mark - 设置nav

-(void)setNav
{
    UISearchBar *searchBar = [[UISearchBar alloc]init];
    self.searchBar = searchBar;
    self.navigationItem.titleView = searchBar;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@" 确认" style:UIBarButtonItemStylePlain target:self action:@selector(jumpToSearchView)];
    
}

#pragma mark - 加载热门界面
-(void)setupUI
{
    //布局第一个热门View
    CNHotView *hotView = [[CNHotView alloc]init];
    __weak typeof(self) weakSelf = self;
    hotView.block = ^(NSString *str)
    {
        NSLog(@"%@",str);
        [weakSelf.searchBar setText:str];
        //跳转第二个view
        [weakSelf jumpToSearchView];
    };
    self.hotView = hotView;
    [self.view addSubview:hotView];
    
    
    
    //约束
    [hotView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(64);
        make.left.bottom.right.offset(0);
    }];
    
    
}
#pragma mark - 跳转搜索页面
-(void)jumpToSearchView
{
    
    //放弃第一响应者，等于放弃了编辑，就会调用结束编辑的方式
    [self.searchBar resignFirstResponder];
    //清除购物车控件
    [self remove];
    
    //布局collectionview
    CNSearchView *searchView = [[CNSearchView alloc]init];
    [self.view addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(64);
        make.left.bottom.right.offset(0);
    }];
    
    //添加购物车控件
    [self setBuyCar];
    searchView.searchStr = self.searchBar.text;
    self.searchView = searchView;

    
    //数据加载成功
    __weak typeof(self) weakSelf = self;
    searchView.loadBock = ^(BOOL isLoadData)
    {
        NSLog(@"回传到主控制器：数据加载成功");
        weakSelf.carView.alpha = 1;
        weakSelf.redV.alpha = 1;
        weakSelf.countLabel.alpha = 1;
        
        if (self.count) {
            weakSelf.redV.alpha = 1;
            weakSelf.countLabel.alpha = 1;
            weakSelf.countLabel.text = [NSString stringWithFormat:@"%ld",self.count];
        }else
        {
            weakSelf.redV.alpha = 0;
            weakSelf.countLabel.alpha = 0;
        }
      
        
    };


}
-(void)remove
{
    [self.hotView removeFromSuperview];
    [self.searchView removeFromSuperview];
    [self.carView removeFromSuperview];
    [self.redV removeFromSuperview];
    [self.countLabel removeFromSuperview];
    
}

-(void)setBuyCar
{
    
    //创建购物车view
    UIView *carView = [[UIView alloc]init];
    carView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:carView];
    [carView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-40);
        make.bottom.offset(-40);
        make.width.height.offset(60);
    }];
    //圆角
    carView.layer.cornerRadius = 30;
    carView.layer.masksToBounds = YES;
    carView.alpha = 0;
    self.carView = carView;
    
    //添加背景图片
    UIImageView *carImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"v2_coupon_verify_normal"]];
    [carView addSubview:carImageView];
    
    [carImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    
    //添加购物车button
    UIButton *Carbutton = [UIButton buttonWithType:UIButtonTypeSystem];
    [Carbutton setTintColor:[UIColor whiteColor]];

    [Carbutton setImage:[UIImage imageNamed:@"shopCart"] forState:UIControlStateNormal];
    [Carbutton addTarget:self action:@selector(jumpShoping) forControlEvents:UIControlEventTouchUpInside];
    
    [carView addSubview:Carbutton];
    
    [Carbutton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    //添加红点标记
    UIImageView *redV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"reddot"]];
    
    [self.view addSubview:redV];
    self.redV = redV;
    self.redV.alpha = 0;
    [redV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(carView).offset(20);
        make.centerY.equalTo(carView).offset(-20);
        make.width.height.offset(18);
    }];
    
    //添加红点个数
    UILabel *countLabel = [[UILabel alloc]init];
    //内容（颜色+字体）
    countLabel.textColor = [UIColor whiteColor];
    countLabel.font = [UIFont systemFontOfSize:13];
    
    [countLabel sizeToFit];
    self.countLabel = countLabel;
    self.countLabel.alpha = 0;
    [redV addSubview:countLabel];

    [countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(redV).offset(0);
    }];
}



#pragma mark - 核心动画：自定义代理 cell点击加号

// MARK:5.使用代理方法 - cell点击加号
- (void)shopDetailOrderSelectedCell:(CNSearchViewCell*)selectedCell didClickImageView:(UIImageView*)selecedImageView
{
    
    // 转坐标  cell -> self.view
    //    CGPoint start = [shopDetailOrderFoodCell convertPoint:addButton.center toView:[UIApplication sharedApplication].keyWindow];
    
    CGPoint start = [selectedCell convertPoint:selecedImageView.center toView:self.view.window];
    
    
    // 1.做什么动画
    CAAnimationGroup* group = [[CAAnimationGroup alloc] init];
    // MARK:进入购物车路径动画
    CAKeyframeAnimation* anim = [[CAKeyframeAnimation alloc] init];
    // 修改位置
    anim.keyPath = @"position";
    
//    // 设置时间
//    anim.duration = 2;
    
    //    // 不让核心动画回来
    //    anim.fillMode = kCAFillModeForwards;
    //    anim.removedOnCompletion = NO;
    
    // 画曲线
    UIBezierPath* path = [UIBezierPath bezierPath];
    [path moveToPoint:start];
    
    //转化坐标系
    // 转坐标 购物车 -> self.view
    
    CGPoint end = self.carView.center;
    
    
    [path addQuadCurveToPoint:end  controlPoint:CGPointMake(start.x+100, start.y-200)];
    // 设置路径
    anim.path = path.CGPath;
    
    
    //设置代理（隐式代理，不遵守协议）走销毁方法
    
    // 创建小红点
    UIImageView* redPointView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, (self.view.bounds.size.width-30) / 2, 160)];
    redPointView.image = selecedImageView.image.copy;
    redPointView.center = start;
    [self.view.window addSubview:redPointView];
    
    
    
    
    // MARK:自旋转动画
    // 1.创建动画对象(做什么动画)
    CABasicAnimation* anim1 = [[CABasicAnimation alloc] init];
    
    // 2.修改动画的属性(怎么做动画)
    // 修改的属性
    anim1.keyPath = @"transform.rotation";
    
    // 累加
    anim1.byValue = @(M_PI * 2 * 3); // 一圈

    
    //缩放
    CABasicAnimation *anim2 = [CABasicAnimation animation];
    anim2.toValue = [NSValue valueWithCGSize:CGSizeMake(0.1, 0.1)];
    anim2.keyPath = @"transform.scale";
    anim2.removedOnCompletion = YES;
    anim2.fillMode = kCAFillModeForwards;
    
    
    
    group.delegate = self;

    // MARK:添加核心动画
    group.animations = @[ anim,anim1,anim2 ];
    // 设置时间
    group.duration = 1;
//    // 设置重复次数
//    group.repeatCount = MAXFLOAT;
    //设置的时候 写在添加核心动画之前
    [group setValue:redPointView forKey:@"redPointView"];
//    [redPointView.layer addAnimation:anim forKey:nil];
    [redPointView.layer addAnimation:group forKey:nil];
    
}
#pragma mark - 核心动画完成
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //在动画结束的时候,通过不同的anim对象,取同样的key.就可以获取到每次做动画的iamgeView
    UIView *view = [anim valueForKey:@"redPointView"];
    NSLog(@"%@",view);
    [view removeFromSuperview];
}

#pragma mark - 通知方法
-(void)addButtonClick:(NSNotification *)notification
{
    self.selectedCell = notification.userInfo[@"selectCell"];
    self.selecedImageView = notification.userInfo[@"selecedImageView"];
    [self shopDetailOrderSelectedCell:self.selectedCell didClickImageView:self.selecedImageView];
    
    [self shakeToShow:self.countLabel];
    [self shakeToShow:self.redV];

    
}
-(void)buyCarCount:(NSNotification *)notification
{
    self.count = [notification.userInfo[@"totalCount"] intValue];

    if ((self.count) != 0) {
        self.redV.alpha = 1;
        self.countLabel.alpha = 1;
        self.countLabel.text = [NSString stringWithFormat:@"%ld",(long)self.count];
    }
    else
    {
        self.redV.alpha = 0;
        self.countLabel.alpha = 0;
    }
    
}



- (void) shakeToShow:(UIView*)aView{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.8;
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}

#pragma mark - 销毁
-(void)dealloc{
    // 在dealloc 的时候 一定要出 移除监听者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"死掉了");
}

#pragma mark - 跳转到购物车页面
-(void)jumpShoping
{
//    UINavigationController *nav = self.navigationController.tabBarController.childViewControllers[2];
//    [self.navigationController pushViewController:nav.childViewControllers[0] animated:YES];
}

@end
